<script setup lang="ts">
import TileItem from '@/components/tiles/item/TileItem.vue'
import {onMounted, ref, watchEffect} from 'vue';

const props = defineProps({
    // 麻将牌编码
    tiles: { type: Array<string>, required: true }
}) 

let oppositePlayedTiles = ref(null);
let transformStyleColArr = ref(new Array<Array<string>>());
// 这里做一次翻转，因为是从右往左排列的
// tiles.reverse();
let tilesColArr = ref(new Array<Array<string>>()); 
let colTransformStyles = ref(new Array<string>());

function loadStyles() {
  oppositePlayedTiles.value = null;
  transformStyleColArr.value = new Array<Array<string>>();
  // 这里做一次翻转，因为是从右往左排列的
  // tiles.reverse();
  tilesColArr.value = new Array<Array<string>>(); 
  colTransformStyles.value = new Array<string>();
  if (oppositePlayedTiles.value == null) {
    return;
  }
  // 一行最多容纳的麻将
  let oneColCount = Math.floor((oppositePlayedTiles as any).value.offsetWidth / 64);
  // 总列数
  let totalRow = Math.ceil(props.tiles.length / oneColCount);
  // 判断数值是否是正负无穷大，如果是无穷大，则认为是无效
  if (!Number.isFinite(totalRow)) {
    return;
  }
  for (var i=0; i<totalRow; i++) {
    // 当前列的麻将
    let colTiles = new Array();
    let startIndex = i*oneColCount;
    let endIndex = oneColCount * (i+1);
    for (let j = startIndex; j < endIndex; j++) {
      if (j < props.tiles.length) {
        colTiles.push(props.tiles[j])
      } else {
        break;
      }
    }
    tilesColArr.value[totalRow -1 - i] = colTiles;
    colTransformStyles.value[i] = `translateY(${((totalRow - i)*7)}px)`
  }
}
// 基础旋转角度
let baseTransformStyle = "rotateX(30deg) rotateZ(180deg)";

onMounted(() => {
  loadStyles();
})

watchEffect(() => {
  loadStyles();
})
</script>

<template>
  <div class="opposite-played-tiles" ref="oppositePlayedTiles">
    <div class="opposite-played-tiles-col" v-for="(cvalue, cindex) in tilesColArr" :key="cindex" :style="{transform: colTransformStyles[cindex], 'z-index': 2100 + cindex}">
      <template v-for="(tile, index) in cvalue" :key="index">
        <TileItem :code="tile" :transformStyle="baseTransformStyle" style="margin-left: 0.8px" :scale="0.7"></TileItem>
      </template>
    </div>
  </div>
</template>

<style scoped lang="scss">
.opposite-played-tiles{
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: center;
  &-col {
    width: 100%;
    display: flex;
    flex-direction: row-reverse;
    justify-content: flex-start;
  }
}
</style>
